package com.nmcc.app_adherence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Calendar;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class ExportActivity extends Activity {
	private static String CSV_NAME = "GPSData.csv";
	private static String CSV_NAME_PERSONS = "Persons.csv";
	   //the record'
		private static String place_name;
		private static String house_number;
		private static String cluster_number;
		private static String house_guid;
		private static String comment;
		private static String household_id;
		private static double longitude;
		private static double latitude;
		private static boolean Dontsaverecord=true;
		
	    // GPSTracker class
	    GPSTracker gps;
	    
	    Persons pers;
	    MergeCSV mergcsvClss;
	   // DataBaseHelper myDbHelper;
	    private Spinner spinner1, spinner2;
	    private Button button;
	    private Spinner spnHHResultspn;
	    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_export);
		
        
	        
	        //Button b = (Button) findViewById(R.id.btnGo_To_Persons);
	       // b.setOnClickListener(new View.OnClickListener() {
	          // public void onClick(View arg0) {
	          // Intent i = new Intent(HouseActivity.this, Persons.class);
	          // startActivity(i);
	           //}
	        //});
	        
	        
	        Button b44 = (Button) findViewById(R.id.btnExportDataToCSVGPSData);
	        b44.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	   //ExportGPSDataToCSV(arg0);
	        	   
	        	   //Toast.makeText(getApplicationContext(), "Now send the exported GPSData csv files via bluetooth using the button below.", 5000).show();
	        	   //SendFileViaBluetoothFromSDCardFolder(arg0, "GPSData.csv");
	           }
	        });
	       
	        Button b55 = (Button) findViewById(R.id.btnExportDataToCSVPersons);
	        b55.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	  // ExportGPSDataToCSV(arg0);
	        	   
	        	 //  Toast.makeText(getApplicationContext(), "Now send the exported Persons csv files via bluetooth using the button below.", 5000).show();
	        	 //  SendFileViaBluetoothFromSDCardFolder(arg0, "Persons.csv");
	           }
	        });
	           
	  
	        Button btnmergeCSV = (Button) findViewById(R.id.btnMergeCSVFiles);
	        btnmergeCSV.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	   //MergeMultipleCSV(arg0);
	           }
	        });
	        
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.export, menu);
		return true;
	}

	
	 
  
  
  
  public void SendMergedCSVToODK(View view){
  	//for now GPSData
  	//try {
  	//final Context context = this;
  	
     //	 if (Mergedgpsfilespresent(context)){
     		 	//String source = Environment.getExternalStorageDirectory().toString() + "/bluetooth/GPSData.csv";
     		    //String destination = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household/forms/Adherence_Phone_1/GPSData.csv";
     		 //sdcard/opendatakit/survey/tables/household/forms/Adherence_Phone_1
     		//CopyFile(source,destination);
         // }
    	  Toast.makeText(getApplicationContext(), "Please make sure that you put csv files into the bluetooth folder, sending from various phones.", Toast.LENGTH_LONG).show();

    	  MergeCSV merg = new MergeCSV();
 	   //to avoid overwriting in odk survey just send to sd card folder
        // add Books
        //db.DropAllTables();
      merg.launchProcedure(this, 1);//gps house merge send to odk
      merg.launchProcedure(this, 3);//persons merge send to odk
      merg.launchProcedure(this, 5);//give to nets
      merg.launchProcedure(this, 6);//give to member
      merg.launchProcedure(this, 7);//give to malaria
        merg.launchProcedure(this, 8);//give to household new
  
       //db.getGPSRecordsCount();
  }
  
  
  
  public boolean MergedPersonsfilespresent(Context context){
      boolean alreadyExists2 = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/Persons.csv").exists();
      
   if (alreadyExists2) {
   	return true;
     }
   else{
   	Toast.makeText(context, "Please make sure that the bluetooth folder contains the merged Persons.csv file in order for you to proceed.", Toast.LENGTH_LONG).show();
       // Files: Input
   	return false;
   }
}



public boolean Mergedgpsfilespresent(Context context){
   boolean alreadyExists = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/GPSData.csv").exists();
if (alreadyExists) {
	return true;
  }
else{
	Toast.makeText(context, "Please make sure that the bluetooth folder contains the merged GPSData.csv file in order for you to proceed.", Toast.LENGTH_LONG).show();
    // Files: Input
	return false;
}
} 
  

  
	




private static void generateCsvFile(String sFileName)
{

	try
	{

		
	String outputFile =Environment.getExternalStorageDirectory() + sFileName;
	
	// before we open the file check to see if it already exists
	boolean alreadyExists = new File(outputFile).exists();

	    //FileWriter writer = new FileWriter(sFileName);
		File root = Environment.getExternalStorageDirectory();
		File gpxfile = new File(root, sFileName);
		FileWriter writer = new FileWriter(gpxfile, true);
		         		
		//count lines if already has data

	// if the file didn't already exist then we need to write out the header line
	if (!alreadyExists)
	{
	    writer.append("House_Guid");
 	    writer.append(',');
 	    writer.append("HouseNumber");
 	    writer.append(',');
 	    writer.append("ClusterNumber");
	    writer.append(',');             	    

 	    writer.append("PlaceName");
 	    writer.append(',');
 	    writer.append("Comment");
 	    writer.append(',');
 	    writer.append("Longitude");
 	    writer.append(',');
 	    writer.append("Latitude");
 	    writer.append(',');
 	    writer.append("HDOP");
 	    writer.append(',');
 	    writer.append("household_id");
 	    writer.append('\n');  

	}		

		//now add the data, same order as above, check corresponding fields

	    writer.append(house_guid);
	    writer.append(',');
	    writer.append(house_number);
	    writer.append(',');
	    writer.append(cluster_number);
	    writer.append(',');
	             	    
	    writer.append(place_name);

	    writer.append(comment);
	    writer.append(',');
	    writer.append(String.valueOf(longitude));
	    writer.append(',');
	    writer.append(String.valueOf(latitude));

	    writer.append("");//no hdop
	    writer.append(',');

	    writer.append(household_id);
	    writer.append('\n');
	    //generate whatever data you want

	    writer.flush();
	    writer.close();
	    
	    
	}
	catch(IOException e)
	{
	     e.printStackTrace();
	} 
 }


public void CopyFile(String sourceFullFileName, String DestinationFullFileName)
  {    
      InputStream inStream = null;
      OutputStream outStream = null;
      try{

          File file1 =new File(sourceFullFileName);
          File file2 =new File(DestinationFullFileName);

          inStream = new FileInputStream(file1);
          outStream = new FileOutputStream(file2); // for override file content
          //outStream = new FileOutputStream(file2,<strong>true</strong>); // for append file content

          byte[] buffer = new byte[1024];

          int length;
          while ((length = inStream.read(buffer)) > 0){
              outStream.write(buffer, 0, length);
          }

          if (inStream != null)inStream.close();
          if (outStream != null)outStream.close();

          System.out.println("File Copied..");
      }catch(IOException e){
          e.printStackTrace();
      }
  }
	




}
